#!/bin/bash

# ============================================
# Web3管理平台 - 完全卸载脚本
# 支持彻底清理所有相关组件
# ============================================

set -e

readonly GREEN='\033[0;32m'
readonly BLUE='\033[0;34m'
readonly YELLOW='\033[1;33m'
readonly RED='\033[0;31m'
readonly NC='\033[0m'

echo -e "${RED}"
echo "╔════════════════════════════════════════════════════════╗"
echo "║              Web3管理平台 - 完全卸载                  ║"
echo "║              ⚠️  这将删除所有数据和配置              ║"
echo "╚════════════════════════════════════════════════════════╝"
echo -e "${NC}"

# 检查当前用户和安装路径
check_installation() {
    echo "🔍 检查安装情况..."

    # 检查可能的安装路径
    POSSIBLE_PATHS=(
        "./web3-management"
        "/home/$USER/web3-management"
        "$(pwd)"
    )

    INSTALL_DIR=""
    for path in "${POSSIBLE_PATHS[@]}"; do
        if [[ -d "$path" && -f "$path/docker-compose.yml" ]]; then
            INSTALL_DIR="$path"
            echo "✅ 发现安装目录: $INSTALL_DIR"
            break
        fi
    done

    if [[ -z "$INSTALL_DIR" ]]; then
        echo "⚠️  未找到标准安装目录，将清理当前目录和Docker容器"
        INSTALL_DIR="$(pwd)"
    fi
}

# 停止和删除容器
remove_containers() {
    echo "🛑 停止和删除容器..."

    cd "$INSTALL_DIR" 2>/dev/null || true

    # 停止docker-compose服务
    if [[ -f "docker-compose.yml" ]]; then
        echo "📦 停止docker-compose服务..."
        docker-compose down --volumes --remove-orphans 2>/dev/null || true
    fi

    # 强制删除相关容器
    echo "🗑️  删除Web3相关容器..."
    docker ps -a --format "{{.Names}}" | grep -E "web3-|web3_" | xargs -r docker rm -f 2>/dev/null || true

    # 删除相关镜像
    echo "🗑️  删除Web3相关镜像..."
    docker images --format "{{.Repository}}:{{.Tag}}" | grep -E "web3|web3_management" | xargs -r docker rmi -f 2>/dev/null || true

    echo "✅ 容器和镜像清理完成"
}

# 删除数据卷
remove_volumes() {
    echo "💾 删除数据卷..."

    # 删除命名卷
    docker volume ls --format "{{.Name}}" | grep -E "web3|mysql_data|redis_data" | xargs -r docker volume rm -f 2>/dev/null || true

    echo "✅ 数据卷清理完成"
}

# 删除网络
remove_networks() {
    echo "🌐 删除网络..."

    docker network ls --format "{{.Name}}" | grep -E "web3" | xargs -r docker network rm 2>/dev/null || true

    echo "✅ 网络清理完成"
}

# 停止系统服务
remove_systemd_service() {
    echo "🔧 删除系统服务..."

    if systemctl is-active --quiet web3-management 2>/dev/null; then
        echo "🛑 停止系统服务..."
        sudo systemctl stop web3-management 2>/dev/null || true
    fi

    if systemctl is-enabled --quiet web3-management 2>/dev/null; then
        echo "❌ 禁用系统服务..."
        sudo systemctl disable web3-management 2>/dev/null || true
    fi

    if [[ -f "/etc/systemd/system/web3-management.service" ]]; then
        echo "🗑️  删除服务文件..."
        sudo rm -f /etc/systemd/system/web3-management.service
        sudo systemctl daemon-reload
    fi

    echo "✅ 系统服务清理完成"
}

# 删除管理脚本
remove_management_script() {
    echo "📝 删除管理脚本..."

    if [[ -f "/usr/local/bin/web3-mgmt" ]]; then
        sudo rm -f /usr/local/bin/web3-mgmt
        echo "✅ 管理脚本已删除"
    fi
}

# 删除安装目录
remove_installation_directory() {
    echo "📁 删除安装目录..."

    if [[ "$INSTALL_DIR" == "$(pwd)" ]]; then
        echo "⚠️  当前在安装目录中，仅删除项目文件..."
        rm -rf docker-compose.yml .env logs config nginx backend frontend init.sql *.sh .git 2>/dev/null || true
    else
        echo "🗑️  删除完整安装目录: $INSTALL_DIR"
        sudo rm -rf "$INSTALL_DIR" 2>/dev/null || true
    fi

    echo "✅ 安装目录清理完成"
}

# 清理Docker系统
cleanup_docker_system() {
    echo "🧹 清理Docker系统..."

    # 清理未使用的镜像、容器、网络
    docker system prune -f --volumes 2>/dev/null || true

    echo "✅ Docker系统清理完成"
}

# 删除用户和组（可选）
remove_user() {
    if [[ $EUID -eq 0 && -n "$1" ]]; then
        echo "👤 删除服务用户..."

        if id "$1" &>/dev/null; then
            userdel -r "$1" 2>/dev/null || true
            echo "✅ 用户 $1 已删除"
        fi
    fi
}

# 显示卸载完成信息
show_completion() {
    clear
    echo -e "${GREEN}"
    echo "╔══════════════════════════════════════════════════════════╗"
    echo "║                    🎉 卸载完成！                         ║"
    echo "╚══════════════════════════════════════════════════════════╝"
    echo -e "${NC}"

    echo "✅ 以下组件已完全清理："
    echo "  🛑 所有容器和镜像"
    echo "  💾 所有数据卷"
    echo "  🌐 所有网络"
    echo "  🔧 系统服务"
    echo "  📝 管理脚本"
    echo "  📁 安装目录"
    echo ""
    echo "🔄 如需重新安装，请运行："
    echo -e "${BLUE}curl -fsSL https://gitee.com/0616_652/web3_management/raw/main/install.sh | bash${NC}"
    echo ""
    echo "⚠️  注意：所有数据已永久删除，无法恢复！"
}

# 主卸载流程
main() {
    echo "⚠️  即将完全卸载Web3管理平台"
    echo "   这将删除所有数据、配置和相关文件"
    echo ""
    read -p "确认继续？输入 'yes' 确认: " confirm

    if [[ "$confirm" != "yes" ]]; then
        echo "❌ 用户取消卸载"
        exit 0
    fi

    echo "🚀 开始卸载过程..."
    echo ""

    check_installation
    remove_containers
    remove_volumes
    remove_networks
    remove_systemd_service
    remove_management_script
    remove_installation_directory
    cleanup_docker_system

    # 如果是root用户，询问是否删除服务用户
    if [[ $EUID -eq 0 ]]; then
        read -p "是否删除web3服务用户？(y/N): " delete_user
        if [[ $delete_user =~ ^[Yy]$ ]]; then
            remove_user "web3"
        fi
    fi

    show_completion
}

# 错误处理
trap 'echo -e "\n❌ 卸载过程中出现错误"; exit 1' ERR

# 执行主流程
main "$@"
